package cn.lingyangwl.agile.demo.dynamic_bean;

import cn.lingyangwl.framework.core.utils.spring.SpringUtils;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
@Component
public class BeanDefinitionBuilderExample {

    public void test() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) SpringUtils.getApplicationContext().getAutowireCapableBeanFactory();
            BeanDefinitionBuilder b = BeanDefinitionBuilder.rootBeanDefinition(MyBean01.class)
                    .addPropertyValue("str", i + "");
            b.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
            if (beanFactory.containsBean("myBean01")) {
                beanFactory.removeBeanDefinition("myBean01");
                beanFactory.destroySingleton("myBean01");
            }
            b.setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_ALL);
            beanFactory.registerBeanDefinition("myBean01", b.getBeanDefinition());

            MyBean01 bean = SpringUtils.getBean(MyBean01.class);
            BizBean bizBean = SpringUtils.getBean(BizBean.class);

            if (i == 0) {
                new Thread(() -> {
                    for (int j = 0; j < 10; j++) {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                            bizBean.doSomething();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }
}
